/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { Space, Button, message, Spin, Steps } from 'antd';
import { DrawerForm, ProFormText } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import type { TableItem, BindItem } from '../../_utils/index.d';
import { useSelector } from 'umi';
import {
  getWkdAfterPayAuthList,
  setWkdAfterPayAuth,
  setWkdAfterPayAgainAuth,
  setWkdAfterPayment,
} from '@/services/mini/yjBindDeduction';

interface KbAddSmsDrawerForm {
  item: TableItem;
  visible: boolean;
  actionRef: any;
  onClose: () => void;
}

const { Step } = Steps;
const Index = ({ item, visible, actionRef, onClose }: KbAddSmsDrawerForm) => {
  const { waybill_no = '', status: itemStatus } = item;
  const formRef = useRef<ProFormInstance>();
  const [recordStatus, setRecordStatus] = useState<number>(0);
  const [bindList, setBindList] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const getAtuhList = (param: { waybill_no: string }, _status: number) => {
    setLoading(true);
    getWkdAfterPayAuthList(param).then((res) => {
      setLoading(false);
      const { code, data, msg } = res;
      if (code == 0) {
        setBindList(data);
        const bindStatus =
          data.map((iitem: BindItem) => iitem.deduct_status == '1').indexOf(true) != -1 ? 2 : 1;
        console.log(_status, bindStatus);
        if (_status == 1 && bindStatus == 2) {
          message.success('绑单成功');
          setTimeout(() => {
            setRecordStatus(bindStatus);
            onClose();
            actionRef.current?.reload();
          }, 300);
        }
      } else {
        message.error(msg);
      }
    });
  };
  const onSubmit = async (values: { money: string }) => {
    if (loading) return;
    setLoading(true);
    setWkdAfterPayAuth({ waybill_no, ...values }).then((res) => {
      setLoading(false);
      const { code, msg } = res;
      if (code == 0) {
        setRecordStatus(1);
        getAtuhList({ waybill_no }, 1);
      } else {
        message.error(msg);
      }
    });
  };

  useEffect(() => {
    if (itemStatus) {
      setRecordStatus(Number(itemStatus));
      getAtuhList({ waybill_no }, recordStatus);
    }
  }, [waybill_no]);
  return (
    <DrawerForm
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>绑单扣款</div>
          <Button type='primary' onClick={getAtuhList.bind(this, { waybill_no }, recordStatus)}>
            刷新
          </Button>
        </div>
      }
      formRef={formRef}
      width={winSize === 'xs' ? '80%' : 500}
      visible={visible}
      labelAlign='left'
      layout='horizontal'
      labelCol={{
        span: 5,
      }}
      drawerProps={{
        onClose,
        destroyOnClose: true,
      }}
      submitter={false}
      onFinish={onSubmit}
    >
      <Spin spinning={loading}>
        <Steps
          current={Number(recordStatus)}
          labelPlacement='vertical'
          style={{ paddingBottom: 20 }}
        >
          <Step title='绑单' />
          <Step title='扣款中' />
          <Step title='扣款成功' />
        </Steps>
        {recordStatus == 0 ? (
          <Space direction='vertical' align='center'>
            <ProFormText
              width='sm'
              labelCol={{ span: 8 }}
              name='money'
              label='实际运费金额'
              placeholder='请输入实际运费金额'
              rules={[{ required: true, message: '请输入实际运费金额' }]}
              addonAfter='元'
            />
            <Button type='primary' htmlType='submit'>
              绑单
            </Button>
          </Space>
        ) : (
          <div>
            {bindList.map((iitem: BindItem, index) => {
              const { order_id, status, deduct_status, money, price } = iitem;
              const isBind = status == '0'; //未绑单
              const btnText = isBind
                ? '绑单'
                : deduct_status == '1'
                ? '已扣款'
                : deduct_status == '2'
                ? '扣款中'
                : '扣款';
              const handleOption = () => {
                setLoading(true);
                const api = isBind ? setWkdAfterPayAgainAuth : setWkdAfterPayment;
                api({ order_id }).then((res) => {
                  setLoading(false);
                  const { code, msg } = res;
                  if (code == 0) {
                    message.success(msg);
                    getAtuhList({ waybill_no }, recordStatus);
                  } else {
                    message.error(msg);
                  }
                });
              };
              return (
                <ProFormText
                  key={index + 1}
                  label={`运费${index + 1}`}
                  readonly
                  fieldProps={{
                    value: deduct_status == '1' ? money : price + ' ' + '元',
                  }}
                  addonAfter={
                    btnText && (
                      <Button
                        type='primary'
                        disabled={btnText == '已扣款' || btnText == '扣款中'}
                        onClick={handleOption}
                      >
                        {btnText}
                      </Button>
                    )
                  }
                />
              );
            })}
          </div>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default Index;
